<?php

namespace App\Console\Commands;

use App\Helpers\Logger\SLogger;
use App\Models\Orm\DataUserCount;
use App\Models\Orm\DataProductDetailLog;
use App\Models\Orm\User;
use App\Models\Orm\XjdUser;
use Illuminate\Console\Command;
use App\Models\Orm\DataProductCount as DataProductCountModel;
use Illuminate\Support\Facades\DB;

class DataUserCountCom extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'DataUserCountCom {date?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '用户总览统计脚本';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    private $date;

    /**
     * 预定义要插入count表的数据容器
     * @var array
     */
    private $dataList = [];

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        #记录开始统计日志
        SLogger::getStream()->info('启动' . __CLASS__);

        // 要统计的日期,默认昨天
        $date = date("Y-m-d", strtotime("-1 day"));

        $inputDate = $this->argument('date');

        if ($inputDate) {
            $patten = '/^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/';
            if (!preg_match($patten, $inputDate)) {
                echo "您输入的日期格式不正确!\n";
                SLogger::getStream()->info('您输入的日期格式不正确!');
                return false;
            }
            $date = $inputDate;
        }

        // 设置查询日期
        $this->setDate($date);

        // 处理详情页点击数据
        $this->handleDetailLogs();

        // 处理申请按钮点击量
        $this->handleApplyLogs();

        // 数据插入data_product_count表
        if (!empty($this->dataList)) {
            $res = $this->insertDataProductCount();
        }

        echo "执行成功!\n";

    }

    private function setDate($date)
    {
        if (!$this->date) {
            $this->date = $date;
        }
        return $this->date;
    }

    /**
     * 处理详情页点击次数
     */
    private function handleDetailLogs()
    {
        $dataList = $this->dataList;

        // 用户注册数
        $dayUserRegistes = $this->getUserRegiste();

        if (!empty($dayUserRegistes)) {

            foreach ($dayUserRegistes as $dayUserRegiste) {

                $key = $dayUserRegiste['app_name'];

                if (!isset($dataList[$key])) {

                    // 初始化这个产品统计记录
                    $dataList[$key] = [
                        'detail_ip_list' => [$dayUserRegiste['created_ip']],
                        'app_name' => $dayUserRegiste['app_name'],
                        'pv' => 1,
                        'uv' => 1,
                        'register_total' => 1,
                        'login_total'  => 0,
                    ];

                } else {
                    // 更新这个产品统计记录
                    $dataList[$key]['register_total'] += 1;
                    $dataList[$key]['pv'] += 1;
                    if (!in_array($dayUserRegiste['created_ip'], $dataList[$key]['detail_ip_list'])) {

                        $dataList[$key]['uv'] += 1;
                        $dataList[$key]['detail_ip_list'][] = $dayUserRegiste['created_ip'];

                    }
                }
            }
        }

        $this->dataList = $dataList;
    }

    /**
     * 用户登录数
     */
    private function handleApplyLogs()
    {
        $dataList = $this->dataList;

        // 详情页点击日志记录数据
        $dayUserLogins = $this->getUserLogin();



        if (!empty($dayUserLogins)) {

            foreach ($dayUserLogins as $dayUserLogin) {

                $key = $dayUserLogin['app_name'];

                if (!isset($dataList[$key])) {

                    // 初始化这个产品统计记录
                    $dataList[$key] = [
                        'detail_ip_list' => [$dayUserLogin['created_ip']],
                        'app_name' => $dayUserLogin['app_name'],
                        'register_total' => 0,
                        'login_total'  => 1,
                        'pv' => 1,
                        'uv' => 1,
                    ];

                } else {

                    $dataList[$key]['login_total'] += 1;
                    //判断一下当天是否注册过
                    $start = $this->date . ' 00:00:00';
                    $end = $this->date . ' 24:00:00';
                    $dayUserLogin['registe_time'];
                    if($dayUserLogin['registe_time']>$end || $dayUserLogin['registe_time']<$start){

                        $dataList[$key]['pv'] += 1;

                        if (!in_array($dayUserLogin['created_ip'], $dataList[$key]['detail_ip_list'])) {

                            $dataList[$key]['uv'] += 1;
                            $dataList[$key]['detail_ip_list'][] = $dayUserLogin['created_ip'];

                        }

                    }


                }
            }
        }

        $this->dataList = $dataList;
    }

    /**
     * 某一天注册数
     */
    private function getUserRegiste()
    {
        $start = $this->date . ' 00:00:00';
        $end = $this->date . ' 24:00:00';
        $res = XjdUser::where('registe_time', '>', $start)
            ->where('registe_time', '<=', $end)
            ->get()
            ->toArray();
        return $res ?: [];

    }

    /**
     * 某一天登录人数
     */
    private function getUserLogin()
    {
        $start = $this->date . ' 00:00:00';
        $end = $this->date . ' 24:00:00';
        $res = XjdUser::where('lass_time', '>', $start)
            ->where('lass_time', '<=', $end)
            ->get()
            ->toArray();
        return $res ?: [];

    }

    /**
     * 插入统计表数据
     */
    private function insertDataProductCount()
    {
        $date = $this->date;
        $dataList = $this->dataList;

        foreach ($dataList as $data) {

            $result = DataUserCount::updateOrCreate(['app_name' => $data['app_name'], 'create_date' => $date], [
                'app_name' => $data['app_name'],
                'register_total' => $data['register_total'],
                'login_total' => $data['login_total'],
                'create_date' => $date,
                'pv' => $data['pv'],
                'uv' => $data['uv'],
                'update_at' => date('Y-m-d H:i:s'),
            ]);

            if ($result) {
                SLogger::getStream()->info('产品:' . $data['app_name'] . '统计成功!');
            } else {
                SLogger::getStream()->info('产品:' . $data['app_name'] . '统计失败!');
            }
        }
    }
}
